<template>
  <div class="main-container container-fluid container-box px-2 px-lg-3 ">
    <div class="row">
     <div class="col-lg-9" >
       <!-- 头部编辑区      -->
       <el-card>
         <div>
           <el-input
               v-model="state.model.title"
               maxlength="30"
               style="width: 100%"
               placeholder="请输入标题"
               show-word-limit
               type="textarea"
               autosize
           />
           <el-input
               v-model="state.model.synopsis"
               maxlength="150"
               style="width: 100%;margin-top: 10px"
               placeholder="写一个介绍"
               show-word-limit
               type="textarea"
           />
         </div>

       </el-card>
       <!-- 富文本编辑区       -->
       <el-card STYLE="margin-top: 20px" >
         <div style="border: 1px solid #ccc; z-index: 1000"  >
           <Toolbar
               style="border-bottom: 1px solid #ccc"
               :editor="editorRef"
               :defaultConfig="toolbarConfig"
               :mode="mode"
           />
           <Editor
               style="min-height: 500px; overflow-y: hidden;"
               v-model="state.model.content"
               :defaultConfig="editorConfig"
               :mode="mode"
               @onCreated="handleCreated"
           />
         </div>

       </el-card>

     </div>
      <div class="col-lg-3" >
        <!-- 其他信息编辑区       -->
        <el-card>
          <el-form>
            <el-form-item label="封面图" prop="">
              <el-upload
                  class="avatar-uploader"
                  :action="state.upLoadUrl"
                  :limit="10"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :on-error="handleAvatarError"
                  :before-upload="beforeAvatarUpload"
                  :headers="{token:getToken()}"
              >
                <el-image  v-if="state.imageUrl"  style="width: 100%"  :src="state.imageUrl" alt="" class="avatar"/>
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>
              <div v-loading="state.loading"></div>
            </el-form-item>

            <el-form-item label="标签" prop="tags" >
              <el-input v-model="state.model.tags" placeholder="请输入标签" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>

            <el-form-item label="分类" prop="art_group" >
              <el-input v-model="state.model.artGroup" placeholder="请输入分类" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input v-model="state.model.remark" placeholder="请输入备注" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>

          </el-form>

        </el-card>

        <!--  发布选择      -->
        <el-card style="margin-top: 15px">
          <el-button>存草稿</el-button>
          <el-button type="success" @click="method.userPublishArticle" > 发布博客</el-button>
        </el-card>
      </div>
      </div>
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {onBeforeUnmount, reactive, ref, shallowRef} from "vue";
import {getToken} from "@/utils/tools/auth";
import {ElMessage} from "element-plus";
import {useUserStore} from "@/store/modules/user";
import {formatUrl} from "@/utils/tools/format";
const env = import.meta.env;
let baseUrl= env.VITE_APP_APT_BASEURL;
const userStore = useUserStore();

const  state = reactive({
  upLoadUrl:baseUrl+"/files/upload", //上传路径
  imageUrl:'',//图片路径
  loading:false, //加载
  param:{ //请求参数
    tableData: [],
    /*分页字段 */
    size:10,
    count:1,
    total:0,
    title:'',
    tags:'',
    artGroup:''
  },
  model:{
    id: undefined,    //主键
    uid: userStore.id,   //用户ID
    title: undefined,  //标题
    synopsis: undefined, //简介
    content: undefined, //内容
    covers: undefined,  //封面
    publicize: "一般推流", //推流
    views: undefined,//浏览量
    tags: undefined,//标签
    artGroup: undefined,//分组
    remark: undefined,//备注
    audit: "待审核", //审核
    createTime: undefined, //创建时间
    updateTime: undefined, //更新时间
    state: "已下架", //状态
    json:undefined, //用于存储JSON数据
    text:undefined  //用于存储文本数据
  }
})

const method ={
  /**
   * 发布文章
   */
  userPublishArticle: async ()=>{
    console.log(state.model)
    // await publishArticle(state.model).then(res=>{
    //   if (res.code=== "200"){
    //     ElMessage.success(res.msg)
    //     state.model ={};
    //   }
    // })
  }
}





/**  富文本模块  **/
let rules = reactive({});
const mode = 'default';
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {}
}
/**
 * 图片上传配置
 */
editorConfig.MENU_CONF['uploadImage'] = {
  server:baseUrl+'/files/editor/upload',
  maxFileSize: 5 * 1024 * 1024, // 5M
  fieldName: 'file',
  headers: {
    Accept: '*/*',
    token:getToken()
  },
  meta: {
    token: getToken(),
  },
  customInsert(res, insertFn) {
    insertFn(formatUrl(res.data.url), res.data.alt, res.data.href)

  },
}
/**
 * 视频上传配置
 */
editorConfig.MENU_CONF['uploadVideo'] = {
  server: baseUrl+'/files/editor/upload',
  maxFileSize: 500 * 1024 * 1024, // 500M
  fieldName: 'file',
  headers: {
    Accept: '*/*',
    token:getToken()
  },
  meta: {
    token: getToken(),
  },
  customInsert(res, insertFn) {
    const  poster  = "";
    insertFn(formatUrl(res.data.url), poster)
  },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
/** 视频上传配置end  **/


/**
 *  显示内容
 * @param content
 */
const showCont = ref("");
const showContent = (content) => {
  content_dialogVisible.value =true;
  showCont.value =  content;
}


/**  文件上传模块  **/
/**
 *  上传成功回调
 * @param res
 * @param file
 */
const handleAvatarSuccess = (res, file) => {
  state.loading= false;
  state.imageUrl = formatUrl(res);
  state.model.covers = formatUrl(res);
}

const handleAvatarError = (res)=>{
  state.loading= false;
  ElMessage.error(res);
}
/**
 * 文件上传前
 * @param file
 * @returns {boolean}
 */
const beforeAvatarUpload = (file) => {
  state.loading= true;
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isGIF = file.type === 'image/gif';
  const isPG = (isJPG || isPNG ||isGIF)
  const isLt2M = file.size / 1024 / 1024 < 10;
  if (!isPG) {
    state.loading.value= false;
    ElMessage({message: '上传的图片只能是 JPG 或 PNG 和 GIF 格式!', type: 'error',})
  }
  if (!isLt2M) {
    state.loading.value= false;
    ElMessage({message: '上传的图片不能超过10mb', type: 'error',});
  }
  return isPG && isLt2M;
}
/**  end  **/
</script>

<style scoped>
.main-container {
  width: 1600px;
  max-width: 1600px;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
